# Copyright(C) 2023. Huawei Technologies Co.,Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import partial
from multiprocessing import Queue
import numpy as np
import queue
import re
import time
from transformers import AutoTokenizer
import tritonclient.grpc as grpcclient
from tritonclient.utils import *

from base_model import AI_Model

_MODEL_NAME = "chatglm6b"
_MODEL_PATH = ""
_SERVER = ""
_MAX_ITER_TIMES = 2000
_EOF_TOKEN = 2


class UserData:
    def __init__(self):
        self.completed_requests = queue.Queue()


def callback(user_data, result, error):
    user_data.completed_requests.put((result, error))


class Metrics:
    def __init__(self):
        self.first_token_time = 0
        self.avg_decode_time = 0
        self.max_decode_time = 0
        self.full_time = 0
        self.generated_tokens = 0

    def format(self):
        return {
            "FirstTokenTime": self.first_token_time,
            "DecodeTime": self.avg_decode_time,
            "MaxDecodeTime": self.max_decode_time,
            "GenerationTime": self.full_time,
            "GeneratedTokens": self.generated_tokens,
        }


class MockModeClient:
    def __init__(
        self,
        input_array,
        request_id="0",
        triton_url=_SERVER,
        model_name=_MODEL_NAME,
        eof_token=_EOF_TOKEN,
        max_iter_times=_MAX_ITER_TIMES,
        verbose=False,
    ):
        self.inputs = [
            grpcclient.InferInput("INPUT_IDS", list(input_array.shape), "INT64")
        ]
        self.inputs[0].set_data_from_numpy(input_array)
        self.outputs = [grpcclient.InferRequestedOutput("OUTPUT_IDS")]
        self.triton_url = triton_url
        self.request_id = request_id
        self.model_name = model_name
        self.eof_token = eof_token
        self.verbose = verbose
        self.max_iter_times = max_iter_times
        self.metrics = Metrics()

    def infer(self, tokenizer, input_data, output_queue, metrics=False):
        begin_time = time.time()
        user_data = UserData()
        with grpcclient.InferenceServerClient(
            url=self.triton_url, verbose=self.verbose
        ) as triton_client:
            triton_client.start_stream(callback=partial(callback, user_data))
            triton_client.async_stream_infer(
                model_name=self.model_name,
                inputs=self.inputs,
                request_id=self.request_id,
                outputs=self.outputs,
            )

            last_token_time = time.time()
            decode_full_time = 0
            sentence_list = []
            sentence = ""
            lazy_put = False
            is_end = False

            for _ in range(self.max_iter_times):
                (output_tensor, error) = user_data.completed_requests.get()
                if error is not None:
                    raise error
                token = output_tensor.as_numpy("OUTPUT_IDS")[0]

                if metrics:
                    self.metrics.generated_tokens += 1
                    if self.metrics.first_token_time == 0:
                        self.metrics.first_token_time = time.time() - last_token_time
                    else:
                        decode_time = time.time() - last_token_time
                        decode_full_time += decode_time
                        if decode_time > self.metrics.max_decode_time:
                            self.metrics.max_decode_time = decode_time
                    last_token_time = time.time()

                if lazy_put:
                    if token == self.eof_token:
                        response = "".join(sentence_list)
                        history = [[input_data["query"], response]] + input_data[
                            "history"
                        ]
                        is_end = True
                        output_queue.put(
                            dict(is_end=is_end, sentence=sentence, history=history)
                        )
                        break
                    else:
                        output_queue.put(
                            dict(is_end=False, sentence=sentence, history=[])
                        )
                        sentence = ""
                        lazy_put = False

                decode_token = tokenizer.decode(token)
                sentence += decode_token
                if re.search(r"[，。？！；：]", decode_token):
                    lazy_put = True
                    sentence_list.append(sentence)

            if not is_end:
                sentence_list.append(sentence)
                response = "".join(sentence_list)
                history = [[input_data["query"], response]] + input_data["history"]
                output_queue.put(dict(is_end=True, sentence=sentence, history=history))

            if metrics:
                if self.metrics.generated_tokens > 1:
                    self.metrics.avg_decode_time = decode_full_time / (
                        self.metrics.generated_tokens - 1
                    )
                self.metrics.full_time = time.time() - begin_time

        if metrics:
            print(self.metrics.format)


class LlmModel(AI_Model):
    def __init__(
        self, input_queue, output_queue, init_done_event, model_path=_MODEL_PATH
    ):
        super().__init__(input_queue, output_queue)
        self.tokenizer = AutoTokenizer.from_pretrained(
            model_path, trust_remote_code=True
        )
        init_done_event.set()

    def get_data(self, input_data):
        self.input_queue.put(input_data)

    def run(self):
        while True:
            input_data = self.input_queue.get()
            prompt = self.tokenizer.build_prompt(
                input_data["query"], history=input_data["history"]
            )
            token = self.tokenizer([prompt], return_tensor="np")
            token = token["input_ids"].astype(np.int64)
            input_tensor = token.reshape(1, -1)
            client = MockModeClient(input_tensor)
            try:
                client.infer(self.tokenizer, input_data, self.output_queue, False)
            except Exception as e:
                print(f"Inner Error while runnint client.infer, error message: {e}")


if __name__ == "__main__":
    input_queue = Queue()
    output_queue = Queue()
    llm = LlmModel(input_queue, output_queue)
    init_query = {"query": "你好", "history": []}
    llm.get_data(init_query)
    llm.run()
